# 重写方法指定返回结果
from django.contrib.auth.backends import ModelBackend
from users.models import User
import re

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token':token,
        'username':user.username,
        'user_id':user.id
    }


class MobileNameView(ModelBackend):
    # 重写用户名验证 让用户手机号也可以登录
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 判断username的数据格式
        try:
            if re.match(r'1[3-9]\d{9}',username):
                # 这里的username的意思是用户在登录的时候填写的username或者手机号,因为我们支持手机号登录
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None

        if user is not None and user.check_password(password):
            return user

        return None


